package com.cch.platform.error;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.cch.platform.web.WebUtil;

public class CustomSimpleMappingExceptionResolver extends
		SimpleMappingExceptionResolver {

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		// Expose ModelAndView for chosen error view.
		String viewName = determineViewName(ex, request);
		if (viewName == null){
			return null;
		}
		
		if (request.getHeader("accept").indexOf("application/json") > -1 ||
				(request.getHeader("X-Requested-With")!= null && 
				request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1)){
			// JSON格式返回
			return WebUtil.errorView(ex.getMessage());
		} else {// JSP格式返回
			Integer statusCode = determineStatusCode(request, viewName);
			if (statusCode != null) {
				applyStatusCodeIfPossible(request, response, statusCode);
			}
			return getModelAndView(viewName, ex, request);
		}
	}
}